package com.iqiyi.pps.epg.web.timer;

import com.iqiyi.pps.epg.core.model.sginal.Server;
import com.iqiyi.pps.epg.core.model.sginal.VersionController;
import com.iqiyi.pps.epg.core.service.sginal.ServerService;
import com.iqiyi.pps.epg.core.service.sginal.VersionControllerService;
import com.iqiyi.pps.epg.core.utils.ApiSginalUtil;
import com.iqiyi.pps.epg.core.utils.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * Created by yanchao on 2018/1/5.
 */
public class AutoVersionControllerTrigger {
    private static Logger logger = LoggerFactory.getLogger(VersionControllerService.class);

    @Autowired
    private ServerService serverService;

    @Autowired
    private VersionControllerService versionControllerService;

    public void task() {
        logger.info("[AutoVersionControllerTrigger][start]");
        long startTime = System.currentTimeMillis();
        VersionController newVC = null;
        VersionController oldVC = null;
        String mainVersion = versionControllerService.getMainVersion();
        String ip = null;
        int serverId = -1;
        try {
            List<Server> serverList = serverService.getAllZzd();
            for (Server server : serverList) {
                newVC = null;
                oldVC = null;
                try {
                    serverId = server.getId();
                    ip = serverService.get(serverId).getInsideServerIp();
                    String info = ApiSginalUtil.getVersion(ip);
                    oldVC = versionControllerService.getVersionControllerByServerID(serverId);
                    if (info != null) {
                        newVC = versionControllerService.string2VersionController(serverId,info,mainVersion);
                    }
                }
                catch (Exception e) {
                    logger.error("[AutoVersionControllerTrigger][info][" + ip + " : " + Constants.getCode(Constants.CODE_ERROR_HTTP_RESULT) + "]",e);
                } finally {
                    try {
                        if (newVC == null) {
                            newVC = new VersionController(serverId, VersionController.SERVICE_ACCESS_ABNORMAL);
                        }
                        if (oldVC != null) {
                            newVC.setId(oldVC.getId());
                        }
                        versionControllerService.insertOrUpdate(newVC);
                    } catch (Exception e) {
                        logger.error("[AutoVersionControllerTrigger][error]", e);
                    }
                }
            }

        } catch (Exception e) {
            logger.error("[AutoVersionControllerTrigger][error]", e);
        } finally {
            logger.info("[AutoVersionControllerTrigger][end][time: " + (System.currentTimeMillis() - startTime) + "]");
        }
    }
}
